package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {

        //1.入参判空
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //1-1获取前端传入的用户名和密码
        String password = dto.getPassword();
        String phone = dto.getPhone();

        //2.游-客登录
        if (StringUtils.isEmpty(password) && StringUtils.isEmpty(phone)) {
            //2-1通过用户id生成token，并返回
            String token = AppJwtUtil.getToken(0L);
            Map<String, Object> map = new HashMap<>();
            map.put("user", null);
            map.put("token", token);
            return ResponseResult.okResult(map);
        }

        //3.正常登录
        //3-1创建查询条件
        LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApUser::getPhone, phone);
        ApUser apUser = apUserMapper.selectOne(wrapper);
        //3-2判断用户是否存在，不在则返回结果
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //3-3比对密码
        String salt = apUser.getSalt();
        String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        //3-4判断密码是否相等，不在返回结果
        if (!pswd.equals(apUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //3-5生成token，并返回结果
        String token = AppJwtUtil.getToken(apUser.getId().longValue());

        //3-6清空返回结果里的盐和密码
        apUser.setPassword("");
        apUser.setSalt("");

        //3-7封装入map集合中返回
        HashMap<String, Object> map = new HashMap<>();
        map.put("user", apUser);
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}